/**
 * 
 */
package com.priox.sigar.application.writer;

import com.priox.sigar.client.dto.OperacionCuentaDTO;
import com.priox.sigar.domain.model.AgrupacionRepository;
import com.priox.sigar.util.TimeObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author acogoluegnes
 *
 */
@Component
public class ResumenExcelItemWriter implements ItemWriter<OperacionCuentaDTO> {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ResumenExcelItemWriter.class);

    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private AgrupacionRepository agrupacionRepository;


    @PostConstruct
    public void init() {
        jdbcTemplate=new JdbcTemplate(dataSource);
    }

	/* (non-Javadoc)
	 * @see org.springframework.batch.item.ItemWriter#write(java.util.List)
	 */
	@Override
	public void write(final List<? extends OperacionCuentaDTO> items) throws Exception {
        String sql = "insert into dbo.SGTX_RESUMEN_EXCEL (NUMERO_DOCUMENTO,CODIGO_MONEDA,ACREEDOR_ID,REFERENCIA,SOCIEDAD_ID,FECHA_CREACION) values (?,?,?,?,?,GETDATE())";

        TimeObserver timeObserver = new TimeObserver("insert del bloque en ");
        timeObserver.empezar();
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                OperacionCuentaDTO customer = items.get(i);
                ps.setString(1, customer.getNumeroDocumento());
                ps.setString(2, customer.getCodigoMoneda());
                ps.setString(3, customer.getAcreedorId());
                ps.setString(4, customer.getReferencia());
                ps.setString(5, customer.getSociedadId());
            }

            @Override
            public int getBatchSize() {
                return items.size();
            }
        });
        timeObserver.terminar();
    }

}
